package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.util.AreaInfo;
import com.atguigu.gmall.user.util.BaiDuService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author atguigu
 * @since 2023-05-04
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param userInfo
     * @param httpServletRequest
     * @return
     */
    @Override
    public Map login(UserInfo userInfo, HttpServletRequest httpServletRequest) {
        //1.根据账号(登录,手机号,邮箱号)查询用户记录
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName, userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getEmail, userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getPhoneNum, userInfo.getLoginName());

        //2.将提交密码进行加密
        UserInfo loginUser = this.getOne(queryWrapper);
        //3.判断密码是否一致
        String userEnterPwd = DigestUtils.md5DigestAsHex(userInfo.getPasswd().getBytes());
        if(loginUser.getPasswd().equals(userEnterPwd)){
            //4.验证通过
            //4.1生成令牌UUID
            String token = UUID.randomUUID().toString().replace("-", "").toString();
            String userKey = RedisConst.USER_KEY_PREFIX + token;
            //4.2将用户信息存入redis,key:uuid-->value-->用户信息
            JSONObject userInfoJsonObj = new JSONObject();
            userInfoJsonObj.put("id", loginUser.getId());
            //todo:通过第三方服务根据ip获取城市
            String ipAddress = "221.220.109.97";
            AreaInfo area = BaiDuService.getArea(ipAddress);
            if(area != null){
                //todo:储存设备唯一标识,需要手机端获取手机7硬件信息提交给服务端
                userInfoJsonObj.put("ipCity",area.getCity());
            }
            redisTemplate.opsForValue().set(userKey, userInfoJsonObj, 30, TimeUnit.MINUTES);
            //5.将生成令牌根用户信息响应给客户端浏览器
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("token", token);
            mapResult.put("nickName" ,loginUser.getNickName());
            return mapResult;
        }else{
            throw new RuntimeException("用户名密码错误");
        }
    }


    /**
     * 退出登录
     * @param token
     */
    @Override
    public void logout(String token) {
        //1.构建用户登录时存入tokenKey
        String tokenKey = RedisConst.USER_KEY_PREFIX + token;
        //2.将用户存入的tokenKey删除
        redisTemplate.delete(tokenKey);
    }
}